#include "sceneproject.h"
#include "ui_sceneproject.h"
#include <QDebug>

SceneProject::SceneProject(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UsageScene),
    mqttClient(nullptr)
{
    ui->setupUi(this);
    ///导入场景对应的配置文件 到mSetting数据对象
    mqttClient = new QMQTT::Client(QHostAddress(mSetting.mqttIp),mSetting.mqttPort);
    mqttClient->setUsername(mSetting.useName);
    mqttClient->setPassword(mSetting.usePasswd.toUtf8());
    ui->widget_back->setClient(mqttClient);
    //连接与断开连接
    connect(mqttClient,&QMQTT::Client::connected,this,[=](){
        ui->label_state->setText("已连接");
        ui->pushButton_onoff->setText("断开");
        qDebug()<<Q_FUNC_INFO<<"mqtt服务器已连接!   "<<QString("客户端ID: %1").arg(mqttClient->clientId());
    });
    connect(mqttClient,&QMQTT::Client::disconnected,this,[=](){
        ui->label_state->setText("未连接");
        ui->pushButton_onoff->setText("连接");
        qDebug()<<Q_FUNC_INFO<<"mqtt服务器已断开!";
    });
    //消息的接收与发送
    connect(mqttClient,&QMQTT::Client::received,this,[=](QMQTT::Message mesage)
    {
        qDebug()<<Q_FUNC_INFO<<QString("reciver Topic:%1  Value:%2  Qos:%3")
                            .arg(mesage.topic())
                            .arg(QString::fromUtf8(mesage.payload()))
                            .arg(mesage.qos());
        if(mSetting.recordLog)
            ;///针对该场景，可以插入mqtt日志——接收到消息
        ui->widget_back->receivedMessage(mesage);
    });
    connect(ui->widget_back,&BackWidget::publishMessage,this,[=](QMQTT::Message mesage)
    {
        qDebug()<<Q_FUNC_INFO<<QString("send Topic:%1  Value:%2  Qos:%3")
                            .arg(mesage.topic())
                            .arg(QString::fromUtf8(mesage.payload()))
                            .arg(mesage.qos());
        if(mSetting.recordLog)
            ;///针对该场景，可以插入mqtt日志——发布消息
        mqttClient->publish(mesage);
    });
    if(mSetting.autoConnect)
        mqttClient->connectToHost(); //自动连接
}

SceneProject::~SceneProject()
{
    delete ui;
}

void SceneProject::on_pushButton_onoff_clicked()
{
    if(mqttClient == nullptr)
        return ;
    if(!mqttClient->isConnectedToHost())
    {
        qDebug()<<Q_FUNC_INFO<<"连接mqtt服务器...";
        mqttClient->connectToHost();
    }
    else
    {
        qDebug()<<Q_FUNC_INFO<<"断开mqtt服务器...";
        mqttClient->disconnectFromHost();
    }
}

#include "setmqttdialog.h"
void SceneProject::on_pushButton_setting_clicked()
{
    SetMqttDialog setDialog(mSetting,this);
    if(setDialog.exec() == QDialog::Rejected)
        return;
    mSetting = setDialog.getSetData();
}
